/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
    int cnt = 0, ret = 0;
public:
    int kthSmallest(TreeNode* root, int k) {
        cnt = k;
        dfs(root);
        return ret;
    }
 
    void dfs(TreeNode* root)
    {
        if(root == nullptr || cnt == 0)
            return;
 
        dfs(root->left); // 遍历左子树
        if(--cnt == 0) // 判断
            ret = root->val;
        dfs(root->right); // 遍历右子树
    }
};